<?php
namespace app\admin\controller; 
use think\AjaxPage;
use think\Controller;
use think\Url;
use think\Config;
use think\Page;
use think\Verify;
use think\Db;
class Storegoods extends Base {
	
	
	public function goodsList(){
		return $this->fetch();
	}
	
	//优惠商品列表
	public function discountlist(){
		return $this->fetch();
	}
	
	
	/**
     *  商品列表
     */
    public function ajaxGoodsList(){            
		$this->showAjaxGoodsList();		
		
		$storeid = session('store_id');
		$tList = M('goods_type')->where(['storeid'=>$storeid])->getField("id,typename"); 
		$this->assign('tlist',$tList);
        return $this->fetch('ajaxGoodsList');
    }
	
	//优惠商品列表
	public function ajaxdiscount(){
		$this->showAjaxGoodsList();
        return $this->fetch('ajaxdiscount');
	}
	
    
    public function showAjaxGoodsList(){
    	$storeid = session('store_id');
		
        $where = " storeid= $storeid "; // 搜索条件                
        if(I('isshow') !== '') {
        	$where = "$where and isshow = ".I('isshow');
		}                
		
		$types = I('type/d',0);
		if($types!=0){
			$where = "$where and type= $types ";
		}
		
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and gname like '%$key_word%'" ;
        }
        
        $count = M('goods')->where($where)->count();
        $Page  = new AjaxPage($count,10);

        $show = $Page->show();
		
		if(I('orderby1')!=''){
			$order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
		}
		else{
			$order_str = "addtime desc";
		}
        
        $goodsList = M('goods')->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
    }
    
	
	//添加商品的方法
    function addEditGoodsFun(){
    	$goods_id = I('id');
        $type = $goods_id > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
		$goodstype = I('type');
		$act = '';
        //ajax提交验证
        if ((I('is_ajax') == 1) && IS_POST) {
            // 数据验证
            $data = input('post.');
            $validate = \think\Loader::validate('StoreGoods');
            if (!$validate->batch()->check($data)) {
                $error = $validate->getError();
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                );
                $this->ajaxReturn($return_arr);
            }
			
			
            if ($type == 2) {
            	M('goods')->where("id=$goods_id")->save($data);
				$act = 'update';
            } else {
            	$data['addtime'] = time();
				$storeid = session('store_id');				
				$data['storeid'] = $storeid;	
				$data['isshow'] = 1;				
				M('goods')->add($data);
                $goods_id = $insert_id = M('goods')->getLastInsID();
				
				$this->AddAfter($goodstype,$goods_id);
				$act = 'add';
            }
			
			
            $this->afterSave($goods_id,$act);
			$this->updateAfter($goodstype,$goods_id);		
            $return_arr = array(
                'status' => 1,
                'msg' => '操作成功',
                'data' => array('url' => U($this->typetourl($goodstype))),
            );
            $this->ajaxReturn($return_arr);
        }
		
		
		$goodsid = I('GET.id', 0);
        $goodsInfo = Db::name('goods')->where('id=' .$goodsid)->find();
		$goodsatt = M('goods_att')->where(['gid'=>$goodsid])->select();
        $goodsImages = M("goodsimage")->where('goodsid =' . $goodsid)->select();
		
		$this->assign('goodsInfo', $goodsInfo);  // 商品详情
        $this->assign('goodsImages', $goodsImages);  // 商品相册
        $this->assign('goods_att', $goodsatt);  // 商品属性 
             
    }
	
	//添加编辑商品
	public function addEditGoods(){
       $this->addEditGoodsFun();
	   $storeid = session('store_id');
	   $typeinfo = Db::name('goods_type')->where(['storeid'=>$storeid])->select();
	   
	   $goodsid = I('GET.id', 0);
	   $cresult = Db::view('coupontogoods','*')
	    ->view('coupon','id,cname,iconurl,endtime','coupontogoods.couponid=coupon.id')
	    ->where(['coupontogoods.goodsid'=>$goodsid])
	    ->select();
	   
	   //$typeinfo['0'] = ['id'=>0,'typename'=>'全部'];
	   array_unshift($typeinfo, ['id'=>0,'typename'=>'全部']);
	   $this->assign('typelist',$typeinfo);
	   $this->assign('coupon', $cresult);  // 优惠券   
	   
       return $this->fetch('_goods');
	}
	
	//添加编辑优惠商品
	public function aeDiscount(){
       $this->addEditGoodsFun();
       
       $goodsid = I('GET.id', 0);
	   $cresult = Db::view('coupontogoods','*')
	    ->view('coupon','id,cname,iconurl,endtime','coupontogoods.couponid=coupon.id')
	    ->where(['coupontogoods.goodsid'=>$goodsid])
	    ->select();
	   
	   $this->assign('coupon', $cresult);  // 优惠券 
       
       return $this->fetch('discount');
	}
	
	//不同类型不同刷新的地址
	public function typetourl($type){
		if($type==1){
			return 'admin/Storegoods/goodsList';
		}
		else if($type==2){
			return 'admin/Storegoods/discountlist';
		}
		else if($type==3){
			return 'admin/Storegoods/activitylist';
		}
		else if($type==4){
			return 'admin/Storegoods/informationlist';
		}
		else if($type==5){
			return 'admin/Storegoods/importlist';
		}
		else if($type==6){
			return 'admin/Storegoods/brandlist';
		}
	}

	public function afterSave($goods_id,$act='')
    {    
         // 商品图片相册  图册
         $goods_images = I('goods_images/a');
         if(count($goods_images) > 1)
         {                          
             array_pop($goods_images); // 弹出最后一个             
             $goodsImagesArr = M('goodsimage')->where("goodsid = $goods_id")->getField('id,iconurl'); // 查出所有已经存在的图片
             
             // 删除图片
             foreach($goodsImagesArr as $key => $val)
             {
                 if(!in_array($val, $goods_images)) M('goodsimage')->where("id = {$key}")->delete();
             }
             // 添加图片
             foreach($goods_images as $key => $val)
             {
                 if($val == null)  continue;                                  
                 if(!in_array($val, $goodsImagesArr))
                 {                 
                      $data = array('goodsid' => $goods_id,'iconurl' => $val);
                      M("goodsimage")->insert($data); // 实例化User对象                     
                 }
             }
         }
		 
		 $att = I('att/a',[]);
		 $attvalue = I('attvalue/a',[]);
		 $atype = I('atype/a',[]);		 
		 $attcount = count($att);
		 $attvaluecount = count($attvalue);		 
		 
		 if($attcount>0 && $attcount == $attvaluecount){		 		
		 	if($act!='add'){
		 		//添加的不删除
		 		M('goods_att')->where("gid = $goods_id")->delete();
		 	}
			
		 	foreach($att as $key => $val)
            {
            	$adata = array('gid' => $goods_id,'att' => $val,'attvalue'=>$attvalue[$key],'type'=>$atype[$key]);
                M("goods_att")->insert($adata); // 实例化User对象                     
            }
		 }
		 
		$bindArr=I('coupon_ids/a',[]);
		$bindArrLen = count($bindArr);
		
		
		$allresult = M("coupontogoods")->where(['goodsid'=>$goods_id])->select();
		$allnum = count($allresult);
		
		for($i=0;$i<$bindArrLen;$i++){
			$bindid = $bindArr[$i];
			$result = M('coupontogoods')->where(['couponid'=>$bindid,'goodsid'=>$goods_id])->select();
			if(count($result)>0){
				continue;
			}		
			M('coupontogoods')->add(['goodsid'=>$goods_id,'couponid'=>$bindid,'nums'=>1]);
		}
		
		for($i=0;$i<$allnum;$i++){		
			$couponid = intval($allresult[$i]['couponid']);	
			$bindid = 0;
			$isHave = false;
			$deleteid = intval($allresult[$i]['id']);	
			for($j=0;$j<$bindArrLen;$j++){
				$bindid = intval($bindArr[$j]);		
				if($bindid==$couponid){
					$isHave =  true;
					break;
				}
			}
			
			if(!$isHave){
//				$DB -> query("delete from xl_coupontogoods where id=?",array($deleteid));
				M('coupontogoods')->where(['id'=>$deleteid])->delete();
			}
		}		
    }
	
	//添加方法后续
	public function AddAfter($gtype,$goods_id){
		
		M('goods')->where(['id'=>$goods_id])->save(['sortid'=>$goods_id]);
		if($gtype==1){
		}
		else if($gtype==2){
			$data = [
			    ['gid' => $goods_id,'att' => '有效期','attvalue'=>'','type'=>1],
			    ['gid' => $goods_id,'att' => '可用时间','attvalue'=>'','type'=>1],
			    ['gid' => $goods_id,'att' => '预约提示','attvalue'=>'','type'=>1],
			    ['gid' => $goods_id,'att' => '温馨提示','attvalue'=>'','type'=>1]
			];
            M("goods_att")->insertAll($data);						
		}
		else if($gtype==3){
			
		}
		else if($gtype==4){
			
		}
		else if($gtype==5){
			
		}
	}
	
	//添加项目引进修改
	public function updateAfter($gtype,$goods_id){
		if($gtype==5){
			$data = [];
			$data['id'] = I('i_id');
			$data['gname'] = I('i_gname');
			$data['price'] = 0;
			$data['htmlmsg'] = I('i_htmlmsg');
			$data['icon'] = I('i_icon');
			$data['icon'] = I('i_icon');
			$data['gameurl'] = I('i_gameurl');
			
			
			$data['goodstp'] = 1;
			if(empty($data['gname'])){
				$data['gname'] = $goods_id.'-001';
			}
			//添加对应的资讯
			$this->addimportinfo(true,$goods_id,$data);
		}		
	}
	
	//最新活动
	public function addEditActiye(){
		$this->addEditGoodsFun();
       	return $this->fetch('activity');
	}
	
	//活动列表
	public function activitylist()
	{
		return $this->fetch();
	}
	
	//活动列表
	public function ajaxactivity()
	{
		$this->showAjaxGoodsList();
        return $this->fetch();
	}
	
	//编辑活动
	public function aeActivity(){
		$this->addEditGoodsFun();
       return $this->fetch('activity');
	}
	
	//删除活动
	public function delactivity(){
		$this->deleteGoods();
        $this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storegoods/activitylist")]);
	}
	
	/**
     * 删除商品相册图
     */
    public function del_goods_images()
    {
        $path = I('filename','');
        M('goodsimage')->where("iconurl = '$path'")->delete();
    }
	
	
	
	//删除商品方法
	function deleteGoods(){
		$ids = I('post.ids','');
        $this->deleteGoodsfun($ids);
	}
	
	//删除方法
	function deleteGoodsfun($ids){
		empty($ids) &&  $this->ajaxReturn(['status' => -1,'msg' =>"非法操作！",'data'  =>'']);
        $goods_ids = rtrim($ids,",");
		
		$buyNum = M("buylist")->whereIn('goodsid',$goods_ids)->count();
		if($buyNum > 0){
			$this->ajaxReturn(['status' => -1,'msg' =>"该商品已经被用户购买过"]);
		}
		
        //删除此商品        
        M("goods")->whereIn('id',$goods_ids)->delete();  //商品表
        M("goodsimage")->whereIn('goodsid',$goods_ids)->delete();  //商品相册
        M("coupontogoods")->whereIn('goodsid',$goods_ids)->delete();  //对应券表
        M("goods_att")->whereIn('gid',$goods_ids)->delete();  //对应券表  
	}
	
	//删除商品
	public function delGoods(){		
		$this->deleteGoods();
        $this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storegoods/goodsList")]);
	}
	
	//删除优惠商品
	public function deldiscount(){		
		$this->deleteGoods();
        $this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storegoods/discountlist")]);
	}
	
	//项目类型页
	public function typeindex(){
		return $this->fetch();
	}
	
	//项目类型请求数据
	public function ajaxgoodstypelist(){
		$storeid = session('store_id');			
		$where = " storeid= $storeid "; // 搜索条件                              
        
        $count = M('goods_type')->where($where)->count();
        $Page  = new AjaxPage($count,20);

        $show = $Page->show();
		
		$order_str = "id desc";
        
        $rList = M('goods_type')->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('typelist',$rList);
        $this->assign('page',$show);// 赋值分页输出
        return $this->fetch();
	}
	
	//添加或者修改项目类型
	public function addEditGoodtype(){
		$id = I('id/d',0);
		
		if ((I('is_ajax') == 1) && IS_POST) {
			$atypename = I('typename/s','');
			
			$data = input('post.');
			$validate = \think\Loader::validate('GoodsType');
	        if (!$validate->batch()->check($data)) {
	            $error = $validate->getError();
	            $error_msg = array_values($error);
	            $return_arr = array(
	                'status' => -1,
	                'msg' => $error_msg[0],
	                'data' => $error
	            );
	            $this->ajaxReturn($return_arr);
	        }
			
			$storeid = session('store_id');	
			
			$haveNum = M('goods_type')->where(['typename'=>$atypename,'storeid'=>$storeid])->count();
			if($haveNum > 0){
				$return_arr = array(
	                'status' => -1,
	                'msg' => '名称重复',
	                'data' => ['typename'=>"名称重复"]
	            );
	            $this->ajaxReturn($return_arr);
			}
				
			if($id <= 0){
				$data['storeid'] = 	$storeid;	
				M('goods_type')->add($data);
			}
			else{
				M('goods_type')->where(['id'=>$id])->save($data);
			}
			$this->ajaxReturn(['status' => 1,'msg' => '操作成功','data' =>['url'=>U("Admin/Storegoods/typeindex")]]);
		}
		
		$tinfo = Db::name('goods_type')->where('id='.$id)->find();
        $this->assign('tinfo', $tinfo);  // 商品详情
        return $this->fetch();
	}
	
	//删除角色
	function deltype(){
		$ids = I('post.ids','');
        empty($ids) &&  $this->ajaxReturn(['status' => -1,'msg' =>"非法操作！",'data'  =>'']);
        $goods_ids = rtrim($ids,",");
		
		$tresult = M("goods")->whereIn('goodstp',$goods_ids)->select();
		if(count($tresult)>0){
			$this->ajaxReturn(['status' => -1,'msg' =>"已有项目使用此类型,请先更改对应项目的类型！",'data'  =>'']);
		}
		
        // 删除此角色      
        M("goods_type")->whereIn('id',$goods_ids)->delete();
		$this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storegoods/typeindex")]);
	}
	
	
	//项目引进
	public function importlist(){
		return $this->fetch();
	}
	
	//项目引进刷新
	public function ajaximport(){
		$this->showAjaxGoodsList();
        return $this->fetch('ajaximport');
	}
	
	//最新活动
	public function addeditimport(){
		$this->addEditGoodsFun();
		
		$goodsid = I('GET.id', 0);
        $information = M("import_info")->where('importid =' . $goodsid)->find();
		$infos = [];	
		if(!empty($information)){
			$infos = M("Information")->where('id =' . $information['infoid'])->find();
		}	
		$this->assign('information', $infos);
		//
		//添加资讯信息
       	return $this->fetch();
	}
	
	
	/**
	 * $is_ajax 是否是ajax 
	 * $gid 对应项目引进的id
	 * */
	function addimportinfo($is_ajax,$gid,$data){
		if(!$gid)
			return 0;
		
    	$goods_id = $data['id'];
        $type = $goods_id > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
		$goodstype = 4;
        //ajax提交验证
        if ($is_ajax && IS_POST) {
            // 数据验证
            
            $validate = \think\Loader::validate('Infor');
            if (!$validate->batch()->check($data)) {
                $error = $validate->getError();
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                    'url'=>U("Admin/Storegoods/importlist")
                );
                $this->ajaxReturn($return_arr);
            }
			
			
            if ($type == 2) {
            	M('information')->where("id=$goods_id")->save($data);
            } else {
            	$data['addtime'] = time();
				$storeid = session('store_id');				
				$data['storeid'] = $storeid;	
				$data['isshow'] = 1;
				$data['type'] = 4;				
				M('information')->add($data);
                $goods_id = $insert_id = M('information')->getLastInsID();
            }
			
			//判断是否和项目引进的商品建立了关系
			$connmsg = Db::name('import_info')->where(['importid'=>$gid,'infoid'=>$goods_id])->count();
			if($connmsg<=0 && $goods_id>0){
				Db::name('import_info')->add(['importid'=>$gid,'infoid'=>$goods_id]);
			}
        }
		return $goods_id;    
    }
	
	//删除项目引进商品
	public function delimport(){		
		$this->deleteGoods();
		$ids = I('post.ids','');
        $goods_ids = rtrim($ids,",");
		
		//删除对应资讯
		$connres = Db::name('import_info')->whereIn('importid',$goods_ids)->select();
		$connresArr = [];
		foreach($connres as $k=>$v){
			array_push($connresArr,$v['infoid']);
		}
		if(count($connresArr)>0){
			$connresStr = implode(",",$connresArr);
			//资讯表
			M("information")->whereIn('id',$connresStr)->delete();  
			Db::name('info_game')->whereIn('infoid',$connresStr)->delete();
		}
		
		//删除绑定的关系
		Db::name('import_info')->whereIn('importid',$goods_ids)->delete();
        $this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storegoods/importlist")]);
	}
	
	
	public function brand(){
		$this->addEditGoodsFun();
		return $this->fetch();
	}
	
	public function brandlist(){
		return $this->fetch();
	}
	
	public function delbrand(){
		$this->deleteGoods();
        $this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storegoods/brandlist")]);
	}
	
	public function brandajax(){
		$this->showAjaxGoodsList();
        return $this->fetch();
	}
}
?>